package br.com.caiocarrara.goodbuy.interceptor;

import br.com.caelum.vraptor.InterceptionException;
import br.com.caelum.vraptor.Intercepts;
import br.com.caelum.vraptor.Result;
import br.com.caelum.vraptor.core.InterceptorStack;
import br.com.caelum.vraptor.interceptor.Interceptor;
import br.com.caelum.vraptor.resource.ResourceMethod;
import br.com.caiocarrara.goodbuy.controller.UsersController;
import br.com.caiocarrara.goodbuy.model.UserLogged;

@Intercepts
public class AuthenticateInterceptor implements Interceptor {
	private final UserLogged userLogged;
	private final Result result;
	
	public AuthenticateInterceptor(UserLogged userLogged, Result result) {
		this.userLogged = userLogged;
		this.result = result;
	}
	
	public boolean accepts(ResourceMethod method) {
		return !this.userLogged.isLogged() && method.containsAnnotation(Restrict.class);
	}

	public void intercept(InterceptorStack stack, ResourceMethod method, Object resourceInstance) throws InterceptionException {
		this.result.redirectTo(UsersController.class).loginForm();
	}

}
